package org.example.testdemo.interceptor;


import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.testdemo.tool.ApiResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

public class PermissionBlocking implements HandlerInterceptor {

	/**
	 * 访问控制器方法前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		try {
			//拿出session
			HttpSession session=request.getSession();
			//取出权限
			Integer permissionId = (Integer) session.getAttribute("permissionId");
			if(permissionId==null || permissionId!=1){
				response.getWriter().write(JSONObject.toJSONString(ApiResponse.fail(20000,"无权限进行此操作")));
				return false;
			}
			return true;
		}catch (Exception e){
			response.getWriter().write(JSONObject.toJSONString(ApiResponse.error()));
			return false;
		}
	}

	/**
	 * 访问控制器方法后执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * postHandle方法执行完成后执行，一般用于释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
